package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vo.WmNewsVo;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import sun.plugin.viewer.LifeCycleManager;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    public static final Short COLLECT_MATERIAL = 1;//收藏
    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏
    public static final String WM_NEWS_TYPE_IMAGE = "image";
    public static final Short WM_NEWS_NONE_IMAGE = 0;
    public static final Short WM_NEWS_SINGLE_IMAGE = 1;
    public static final Short WM_NEWS_MANY_IMAGE = 3;
    public static final Short WM_NEWS_TYPE_AUTO = -1;
    public static final Short WM_CONTENT_REFERENCE = 0;
    public static final Short WM_COVER_REFERENCE = 1;
    public static final short WM_NEWS_CONTENT_REFERENCE=1 ;//主图引用

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //参数校验
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //条件查询
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getBeginPubDate()!=null & dto.getEndPubDate()!=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        if (dto.getKeyword()!=null){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //查询登录信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        queryWrapper.eq(WmNews::getUserId,user.getId());
        //日期降序排序

        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        Page page = new Page(dto.getPage(), dto.getSize());
        IPage iPage = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),(int)iPage.getTotal());
        responseResult.setData(iPage.getRecords());
        responseResult.setHost(fileServerUrl);

        return responseResult;
    }

    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //校验参数
        if (dto==null|| StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //对象拷贝 浅拷贝
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        if (WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            wmNews.setImages(dto.getImages().toString().replace("[","").replace("]","").replace(fileServerUrl,"").replace(" ",""));
        }
        //保存WmNews表
        this.saveWmNews(wmNews,isSubmit);
        //提取图片
        String content = dto.getContent();
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> imageList=ectractUrlInfo(list);
        if (isSubmit==WmNews.Status.SUBMIT.getCode()&& imageList.size()>0){
            ResponseResult responseResult = saveRelativeInfo(imageList, wmNews.getId(), WM_NEWS_CONTENT_REFERENCE);
            if (responseResult!=null){
                return responseResult;
            }
        }
        //设置封面
        if (isSubmit==WmNews.Status.SUBMIT.getCode()){
            ResponseResult responseResult=saveRelativeInfoForCover(dto,imageList,wmNews);
            if (responseResult!=null){
                return responseResult;
            }
        }
        kafkaTemplate.send("wmnews",JSON.toJSONString(wmNews.getId()));
        return null;
    }



    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, List<String> imageList, WmNews wmNews) {
        List<String> images = dto.getImages();
        if (dto.getType().equals(WM_NEWS_TYPE_AUTO)){
            //内容中的图片数量小于等于2  设置为单图
            if (imageList.size() > 0 && imageList.size() <= 2) {
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                images = imageList.stream().limit(1).collect(Collectors.toList());
            } else if (imageList.size() > 2) {
                //如果内容中的图片大于2 则设置为多图
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                images = imageList.stream().limit(3).collect(Collectors.toList());
            } else {
                //内容中没有图片，则是无图
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            }
        }
        //修改文章信息
        if (images != null && images.size() > 0) {
            wmNews.setImages(images.toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", ""));
        }
        updateById(wmNews);
        if (images!=null && images.size()>0){
            ResponseResult responseResult=saveRelativeInfoForImage(images,wmNews.getId());
            if (responseResult!=null){
                return responseResult;
            }
        }
        return null;
    }

    private ResponseResult saveRelativeInfoForImage(List<String> images, Integer id) {
        List<String> imageList = new ArrayList<>();
        for (String image : images) {
            imageList.add(image.replace(fileServerUrl,""));
        }
        return saveRelativeInfo(imageList,id,WM_NEWS_CONTENT_REFERENCE);
    }

    private ResponseResult saveRelativeInfo(List<String> materials, Integer newsId, Short type){
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmMaterial::getUrl,materials);
        queryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId());
        List<WmMaterial> list = wmMaterialMapper.selectList(queryWrapper);
        List<String> materialsIds = new ArrayList<>();
        if (list!=null && list.size()>0){
            Map<String, Integer> map = list.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
            for (String val : materials) {
                String materialId = String.valueOf(map.get(val));
                if (null==materialId){
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "应用图片失效");
                }
                materialsIds.add(materialId);
            }
        }
        wmNewsMaterialMapper.saveRelationsByContent(materialsIds,newsId,type);
        return null;
    }
    private List<String> ectractUrlInfo(List<Map> list) {
        List<String> imageList = new ArrayList<>();
        for (Map map : list) {
            if (map.get("type").equals(WM_NEWS_TYPE_IMAGE)){
                String value = (String) map.get("value");
                imageList.add(value.replace(fileServerUrl,""));
            }
        }
        return imageList;
    }

    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        //有id添加没id修改
        if (wmNews.getId()==null){
            save(wmNews);
        }else {
            //修改前先删除关系表
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            updateById(wmNews);
        }
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //参数校验
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        WmNews wmNews = getById(id);
        //文章是否存在
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        WmNews wmNews = getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }

        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));
        removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //检查参数
        if (dto==null||dto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断文章是否存在
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            if(wmNews.getArticleId()!=null) {
                Map<String, Object> mesMap = new HashMap<>();
                mesMap.put("enable", dto.getEnable());
                mesMap.put("articleId", wmNews.getArticleId());
                kafkaTemplate.send("WmNewsDownOrUp", JSON.toJSONString(mesMap));
            }
        }
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public List<Integer> findRelease() {
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getStatus,8).lt(WmNews::getPublishTime,new Date());
        List<WmNews> list = list(queryWrapper);
        List<Integer> resultList = list.stream().map(WmNews::getId).collect(Collectors.toList());

        return resultList;
    }

    @Override
    public ResponseResult findListAndPage(NewsAuthDto dto) {
        //参数校验
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //分页查询
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);
        //查询记录数
        int count = wmNewsMapper.findListCount(dto);
        //返回结果
        ResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(),count);
        responseResult.setData(list);
        return responseResult;
    }

    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //根据id查询文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        WmNewsVo wmNewsVo = new WmNewsVo();

        if (wmNews!=null&&wmNews.getUserId()!=null){
            WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
            BeanUtils.copyProperties(wmNews,wmNewsVo);
            if (wmUser!=null){
                wmNewsVo.setAuthorName(wmUser.getName());
            }
        }
        return wmNewsVo;
    }
}
